#!/usr/bin/python3
# -*- coding: utf-8 -*-

#DrumBox script

import feedparser
import urllib.request
import lxml.html
import datetime

def discountType(steampage):

  try:
    discounttype = lxml.html.document_fromstring(steampage).\
                   xpath("//p[@class='game_purchase_discount_countdown']/text()")[0]+\
                   datetime.datetime.fromtimestamp(round(int((lxml.html.document_fromstring(steampage).\
                   xpath("//div[@class='game_area_purchase_game']/script/text()")[0].\
                   split('discountCountdownDiv')[3].split(' ')[1]))/60/6)*60*6).\
                   strftime('%Y-%m-%d %H:%M:%S')
  except IndexError:
    discounttype = '\'Cause fuck you that\'s why'
  '''
  try:
    print((int(round(lxml.html.document_fromstring(steampage).\
           xpath("//div[@class='game_area_purchase_game']/script/text()")[0].\
           split('discountCountdownDiv')[3].split(' ')[1]/60/6+0.5))))
  except (IndexError, AttributeError) as error:
    print('')
  '''
  return discounttype

def gameTitle(steampage):
  try:
    gametitle = lxml.html.document_fromstring(steampage).xpath("//div[@class='apphub_AppName']/text()")[0]
  except IndexError:
    gametitle = lxml.html.document_fromstring(steampage).xpath("//div[@class='game_name']/div/text()")[0].rstrip().lstrip()
  return gametitle

try:
  lastidfile = open('last_id', 'r')
  lastidlist=lastidfile.read().splitlines()
  lastidfile.close()
except FileNotFoundError:
  lastidlist=''
  print('Can not open last_id file, read all entries')

salesfeed = feedparser.parse('http://www.steamgamesales.com/rss/?region=ru&stores=steam')

discounttype=''
newlastidlist=[]
for salesentry in salesfeed.entries:
  if salesentry.id in lastidlist:
    break
  newlastidlist.append(salesentry.id)
#иногда страница не грузится с первого раза
  try:
    steampage = urllib.request.urlopen(salesentry.link).read().decode('utf-8','ignore')
  except (HTTPError, URLError) as error:
    print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1')
    print('Data of %s not retrieved because %s\nURL: %s', name, error, url)
    print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1')
    continue
  try:
    gametitle=gameTitle(steampage)
  except IndexError:
    print('Error reading steam page, see debug.txt')
    debug=open('debug.txt', 'w')
    debug.write(steampage)
    continue

  if(discounttype != discountType(steampage)):
    discounttype = discountType(steampage)
    print('\n<b>'+discounttype+'</b>')


  gamediscount = '-'+salesentry.title.split(' off ')[0]
  if(int(gamediscount[1:3]) >= 75):
    gamediscount='<b><irony>'+gamediscount+'</b></irony>'
  elif(int(gamediscount[1:3]) >= 50):
    gamediscount='<irony>'+gamediscount+'</irony>'
  elif(int(gamediscount[1:3]) >= 33):
    gamediscount='<b>'+gamediscount+'</b>'

  gameprice = salesentry.title.split('% off ')[1].split(' - Now only ')[1].replace('RUB','руб.')
  print('<a href="'+salesentry.link+'"><b>'+gametitle+'</b></a> '+gamediscount,gameprice)


#  str(datetime.timedelta(seconds=666))
if newlastidlist:
  lastidfile = open('last_id', 'w')
  for item in newlastidlist: lastidfile.write("%s\n" % item)
  lastidfile.close


